package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Zuul会自动配置过滤器
 */
@Component
public class AccessFilter extends ZuulFilter {

    /**
     * 过滤器的类型:pre,routing,post,error
     * @return
     */
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的序号
     * @return
     */
    @Override
    public int filterOrder() {
        return 6;//过滤器的序号为6,默认已经有5个前置过滤器
    }

    /**
     * 判断当前请求,是否需要执行下面的过滤代码
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //调用商品,执行权限判断
        //调用用户或者订单,不执行判断

        //获得当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获得调用的service id
        //String serviceId = (String) ctx.get("serviceId");
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断service id 是否是"item-service"
        return "item-service".equalsIgnoreCase(serviceId);
    }

    /**
     * 过滤代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/kdjsaflf?jwt=adfgafdsgcxgaf
        //获得当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();

        //从上下文得到request对象
        HttpServletRequest request = ctx.getRequest();
        //用request获取 jwt参数
        String jwt = request.getParameter("jwt");
        //如果参数不存在,阻止继续调用
        if (StringUtils.isBlank(jwt)){
            //如果为空,阻止继续调用
            ctx.setSendZuulResponse(false);

            //直接返回响应
            //JsonResult  -  {code:403,msg:"没有登录",data:null}
            String json = JsonResult.build().code(403).msg("没有登录").toString();
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }

        //在当前zuul版本中,这个返回值没有任何功能
        return null;
    }
}
